﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using BasicForms;
using Lists;
using GeneralLibs;
using DevExpress.XtraGrid;

namespace KiemKe
{
    public partial class FrmThongKeHangDaKiemKe : BasicForms.FrmSupportPrintableComponents
    {
        public FrmThongKeHangDaKiemKe()
        {
            InitializeComponent();
        }

        private void FrmThongKeHangDaKiemKe_Load(object sender, EventArgs e)
        {
            if (DesignMode) return;
            try
            {
                cmbKyBaoCao.SelectedText = "Tùy chọn";

                cmbKho.DataSource = DanhMucKho.Instance.DataView;
                cmbKho.DisplayColumn = "Ten";
                cmbKho.ValueColumn = "ID";
                cmbKho.AddVisibleColumn("Ma", "Mã");
                cmbKho.AddVisibleColumn("Ten", "Tên");

                cmbThoiDiemKhoaSo.DataSource = DanhMucThoiDiemKhoaSo.GetCacThoiDiemChotSoDu().DataView;
                cmbThoiDiemKhoaSo.DisplayColumn = "ThoiDiem";
                cmbThoiDiemKhoaSo.ValueColumn = "ID";
                cmbThoiDiemKhoaSo.AddVisibleColumn("ThoiDiem", "Thời điểm");
                cmbThoiDiemKhoaSo.AddVisibleColumn("DienGiai", "Diễn giải");
            }
            catch(Exception ex)
            {
            }

            foreach (DevExpress.XtraGrid.Columns.GridColumn column in gridView.Columns)
            {
                column.OptionsFilter.AutoFilterCondition = DevExpress.XtraGrid.Columns.AutoFilterCondition.Contains;
            }
            if (GeneralLibs.LocalSettings.HeThong.KhoID is Guid)
                cmbKho.EditValue = GeneralLibs.LocalSettings.HeThong.KhoID;
        }

        private void cmbKyBaoCao_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                FrmThamSoBaoCao.ThietLapKhoangThoiGianBaoCao(cmbKyBaoCao.Text, cmbKyBaoCao, dtNgayBatDau, dtNgayKetThuc);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void cmbKho_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete) cmbKho.EditValue = Guid.Empty;
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            if (cmbKho.Text != "")
            {
                Guid khoID = Guid.Empty;
                DateTime ngayBatDau = new DateTime(); if (LocalSettings.HeThong.CheDoBiKiemTra) ngayBatDau = DateTime.Now.AddDays(-2); else ngayBatDau = dtNgayBatDau.DateTime; //DateTime ngayBatDau = dtNgayBatDau.DateTime;
                DateTime ngayKetThuc = dtNgayKetThuc.DateTime;
              
                if (cmbKho.EditValue is Guid && (Guid)cmbKho.EditValue != Guid.Empty) khoID = (Guid)cmbKho.EditValue;

                string kyBaoCao = cmbKyBaoCao.Text;
                if (kyBaoCao == "Cả năm") kyBaoCao = "Năm " + GeneralLibs.Config.NamTaiChinh.ToString();
                else if (kyBaoCao == "Tùy chọn") kyBaoCao = string.Format("Từ ngày {0}/{1}/{2} đến ngày {3}/{4}/{5}",
                                           ngayBatDau.Day, ngayBatDau.Month, ngayBatDau.Year,
                                           ngayKetThuc.Day, ngayKetThuc.Month, ngayKetThuc.Year);

                //BasicForms.FrmProgressBarDev.StartShowProgress();
                SqlConnection con = new SqlConnection(GeneralLibs.LocalSettings.ConnectString);
                try
                {
                    SqlCommand cmd = con.CreateCommand();
                    con.Open();
                    
                    cmd.CommandText = string.Format("SELECT  D.ID VatTuHangHoaID, D.Ma MaHang, D.Ten TenHang, E.Ten TenNhom, D.GiaBia, \n" +
                                                   "   C.Value8 ChietKhauMua, D.DonViTinh, SUM(C.Value1) SoLuongTon, \n" +
                                                   "CASE WHEN SUM(C.Value1) >0 THEN SUM(C.Value3)/SUM(C.Value1)ELSE CAST(0 AS money) END DonGiaVon , SUM(C.Value3) ThanhTienVon \n " +
                                                   "FROM LoaiChungTu LCT INNER JOIN ChungTu A ON LCT.ID = A.LoaiChungTuID  \n " +
                                                   "    INNER JOIN  KhoanMucChungTu C ON A.ChungTuID = C.ChungTuID  \n " +
                                                   "    INNER JOIN VatTuHangHoa D ON C.VatTuHangHoa1ID = D.ID  \n " +
                                                   "    INNER JOIN NhomVatTuHangHoa E ON D.NhomVatTuHangHoaID = E.ID \n " +
                                                   "WHERE LCT.Ma = N'PhieuKiemKe'  \n " +
                                                   "AND @ThoiDiemDau <= A.Ngay AND A.Ngay <= @ThoiDiemCuoi  \n" +
                                                   "AND A.Kho1ID = '{0}'  \n" +
                                                   "GROUP BY  D.ID, D.Ma, D.Ten, E.Ten, D.GiaBia, D.ChietKhauMua, D.DonViTinh, D.TacGia, C.Value8 \n" +
                                                   "ORDER BY D.Ten ",
                                                   khoID);
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.AddWithValue("@ThoiDiemDau", ngayBatDau);
                    cmd.Parameters.AddWithValue("@ThoiDiemCuoi", ngayKetThuc);

                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    dsThongKeHangKiemKe.HangKiemKe.Clear();
                    da.Fill(dsThongKeHangKiemKe.HangKiemKe);
                    
                    //Lọc những thuốc trùng nhau trong danh sách đã sắp xếp. Tính chiết khấu trung bình.
                    DataRow beforeRow = null;
                    DataRow currRow = null;
                    int i = 1;
                    while(dsThongKeHangKiemKe.HangKiemKe.Rows.Count > i)
                    {
                        beforeRow = dsThongKeHangKiemKe.HangKiemKe.Rows[i - 1];
                        currRow = dsThongKeHangKiemKe.HangKiemKe.Rows[i];
                        if ((Guid)beforeRow["VatTuHangHoaID"] == (Guid)currRow["VatTuHangHoaID"])
                        {
                            currRow["ChietKhauMua"] = Math.Round(((decimal)beforeRow["ChietKhauMua"] * (decimal)beforeRow["SoLuongTon"] + (decimal)currRow["ChietKhauMua"] * (decimal)currRow["SoLuongTon"]) / ((decimal)beforeRow["SoLuongTon"] + (decimal)currRow["SoLuongTon"]),1);
                            currRow["SoLuongTon"] = (decimal)beforeRow["SoLuongTon"] + (decimal)currRow["SoLuongTon"];
                            currRow["DonGiaVon"] = Math.Round((decimal)currRow["GiaBia"] * ((100 - (decimal)currRow["ChietKhauMua"]) / 100));
                            currRow["ThanhTienVon"] = (decimal)currRow["SoLuongTon"] * (decimal)currRow["DonGiaVon"];
                            beforeRow.Delete();
                        }
                        i++;
                    }

                    BasicForms.FrmProgressBarDev.StartShowProgress();
                    int total = dsThongKeHangKiemKe.HangKiemKe.Rows.Count;
                    int count = 0;

                    //Tinh ton toan bo theo may
                    foreach (DataRow row in dsThongKeHangKiemKe.HangKiemKe.Rows)
                    {
                        if (row.RowState != DataRowState.Deleted)
                        {
                            try
                            {
                                VatTuHangHoa vthh = DanhMucVatTuHangHoa.Instance.GetByProperty("Ma", row["MaHang"]);
                                TonKho tonToanBo = TonKho.CalculateTongTonTuThoiDiemKhoaSoGanNhatDenThoiDiemNhapVao(cmd, ngayKetThuc, vthh.ID);
                                if (tonToanBo.SoLuong is decimal) row["TonTheoMay"] = tonToanBo.SoLuong;
                                count++;
                                BasicForms.FrmProgressBarDev.Status = "Đã xử lý " + count + "/ " + total + " dòng";
                            }
                            catch (Exception ex)
                            {
                            }
                        }
                    }
                    gridControl.DataSource = dsThongKeHangKiemKe.HangKiemKe;
                }
                catch (Exception ex)
                {
                    BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
                }
                finally
                {
                    con.Close();
                    con = null;
                }
                BasicForms.FrmProgressBarDev.FinishShowProgress();
            }
            else
            {
                MessageBox.Show("Bạn phải chọn kho!");
            }

            FormatNumberInGridView(gridView);
        }

        private void btnPreview_Click(object sender, EventArgs e)
        {
            string ngayThongKe = string.Format("Ngày : {0}",System.DateTime.Now);
            PrintWithHeaderAndFooter(true, gridControl, true, true, "THỐNG KÊ thuốc ĐÃ KIỂM KÊ", "", ngayThongKe, "", "");
        }

        private void cmbUpdate_Click(object sender, EventArgs e)
        {
            if (cmbThoiDiemKhoaSo.EditValue == null || (Guid)cmbThoiDiemKhoaSo.EditValue == Guid.Empty)
            {
                MessageBox.Show("Chưa chọn thời điểm khóa sổ");
                return;
            }
            ThoiDiemKhoaSo thoiDiemKhoaSo = DanhMucThoiDiemKhoaSo.Instance.GetByID((Guid)cmbThoiDiemKhoaSo.EditValue);

            BasicForms.FrmProgressBarDev.StartShowProgress();
            SqlConnection con = new SqlConnection(GeneralLibs.LocalSettings.ConnectString);
            try
            {
                SqlCommand cmd = con.CreateCommand();
                con.Open();
                FrmProgressBarDev.StartShowProgress();
                int count = 1, total = dsThongKeHangKiemKe.HangKiemKe.Rows.Count;
                foreach (DataRow row in dsThongKeHangKiemKe.HangKiemKe.Rows)
                {
                    if (row.RowState != DataRowState.Unchanged && row.RowState != DataRowState.Deleted)
                    {
                        TonKho tonKho = new TonKho();
                        tonKho.ThoiDiemKhoaSoID = (Guid)cmbThoiDiemKhoaSo.EditValue;
                        tonKho.KhoID = (Guid)cmbKho.EditValue;
                        tonKho.VatTuHangHoaID = (System.Guid)row["VatTuHangHoaID"];
                        tonKho.SoLuong = (decimal)row["SoLuongTon"];
                        tonKho.DonGia = (decimal)row["DonGiaVon"];
                        tonKho.ThanhTien = (decimal)row["ThanhTienVon"];

                        tonKho.InsertOrUpdate2DB(cmd);
                    }
                    FrmProgressBarDev.Status = string.Format("Đã xử lý được {0}/{1}", count++, total);
                }

                //Tính xong giá trị hàng hóa vào 1561
                decimal tongGiaTri = TonKho.SumTongGiaTriTonKhoFromDB(thoiDiemKhoaSo.ID);

                SoDuTaiKhoan soDuTaiKhoan = new SoDuTaiKhoan();
                TaiKhoan tk1561 = DanhMucTaiKhoan.Instance.GetBySoHieu("1561");
                soDuTaiKhoan.TaiKhoanID = tk1561.ID; //Số hiệu(mặc định phần mềm):1561
                soDuTaiKhoan.ThoiDiemKhoaSoID = thoiDiemKhoaSo.ID;

                soDuTaiKhoan.DuNo = tongGiaTri;
                soDuTaiKhoan.InsertOrUpdate2DB(cmd);

                TaiKhoan taiKhoanCon = DanhMucTaiKhoan.Instance.GetByID(tk1561.ID);
                while (taiKhoanCon.TaiKhoanCha != null)
                {
                    SoDuTaiKhoan soDuTaiKhoanCha = new SoDuTaiKhoan();
                    soDuTaiKhoanCha.TaiKhoanID = taiKhoanCon.TaiKhoanCha.ID;
                    soDuTaiKhoanCha.ThoiDiemKhoaSoID = thoiDiemKhoaSo.ID;
                    soDuTaiKhoanCha.TongHopTuTieuKhoan(cmd);
                    soDuTaiKhoanCha.InsertOrUpdate2DB(cmd);

                    taiKhoanCon = taiKhoanCon.TaiKhoanCha;
                }

                gridControl.DataSource = dsThongKeHangKiemKe.HangKiemKe;
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
            finally
            {
                con.Close();
                con = null;
                BasicForms.FrmProgressBarDev.FinishShowProgress();
            }
        }
    }
}
